<template>
  <div class="app-container ">

    <div class="filter-container">
      <!-- <el-input v-model="listQuery.phone" placeholder="手机号" style="width: 200px;" class="filter-item" /> -->

      <!-- <el-select v-model="listQuery.status" placeholder="类型" style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="类型" style="width: 90px" class="filter-item">
        <el-option v-for="item in statuse" :key="item" :label="item" :value="item" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getbanner">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
      <-->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        操作者
      </el-checkbox> -->
    </div>

    <el-table v-loading="tableLoading" :data="list" border fit highlight-current-row style="width: 100%">

      <el-table-column align="center" label="ID" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="名称">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column width="200px" align="center" label="简介">
        <template slot-scope="scope">
          <span>{{ scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="图片">
        <template slot-scope="scope">
          <img width="120px" :src="baseimgurl+scope.row.image_url" alt="">
        </template>
      </el-table-column>
      <el-table-column align="center" label="链接">
        <template slot-scope="scope">
          <span>{{ scope.row.link||'-' }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="状态">
        <template slot-scope="scope">
          <span>{{ scope.row.enabled }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="添加时间">
        <template slot-scope="scope">
          <span>{{ scope.row.end_time | formatDate}}</span>
        </template>
      </el-table-column>
      </el-table-column>
      <!-- <el-table-column min-width="300px" label="Title">
        <template slot-scope="{row}">
          <router-link :to="'/report/edit/'+row.id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column min-width="300px" label="Title">
        <template slot-scope="{row}">
          <router-link :to="'/report/edit/'+row.id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column> -->

    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="简介"  >
          <el-input v-model="temp.content" />
        </el-form-item>
        <el-form-item label="链接" >
          <el-input v-model="temp.link" />
        </el-form-item>

        <el-form-item label="图片">
            <el-upload
              action=""
              accept="image/jpeg,image/png"
              :on-change="onUploadxqimg"
              :auto-upload="false"
              :show-file-list="false"
            >
              <el-button slot="trigger" size="small" type="primary">选取</el-button>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button> -->
              <div slot="tip" class="el-upload__tip">
                <p v-if="!temp.image_url">只能上传jpg/png文件，且不能超过1m</p>
                <p v-if="isupload">图片正在上传中...</p>
                <img v-if="imgurl" style="width:150px;" :src="imgurl" alt="">
                <img v-if="temp.image_url" style="width:150px;border:1px solid #f00;" :src="baseimgurl+temp.image_url" alt="">
                <el-button v-if="pic_files" size="small" @click="uploadimgsend" type="primary">点击上传</el-button>
              </div>

            </el-upload>
        </el-form-item>
        <el-form-item label="是否展示">
          <el-switch
            v-model="temp.enabled"
            active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData">
          提交
        </el-button>
      </div>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />



    <!-- <div class="setbox">
      <div class="left box">

        <el-form ref="dataForm" label-position="left" label-width="100px" style="width: 100%; margin-left:50px;">
          <el-row v-for="(ele, idx) in timerules">
            <el-col :span="9">
              <el-form-item label="起始时间" >
                <input type="time" class="inputsty " name="" :value="ele[0]" ref="stime">
              </el-form-item>
            </el-col>

            <el-col :span="9">
              <el-form-item label="结束时间">
                <input type="time" class="inputsty " name="" :value="ele[1]" ref="etime">
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-button v-if ="idx == timerules.length-1" type="primary" @click="addrules()">
                +
              </el-button>
              <el-button  v-if ="idx>=1" type="danger" @click="delrules(idx)">
                -
              </el-button>
            </el-col>
          </el-row>


        </el-form>
      </div>

      <div class="right box">

      </div>
    </div>
    <div slot="footer" class="dialog-footer">

      <el-button type="primary" @click="updateData()">
        保存
      </el-button>
      <el-button type="danger" @click="deleallData()">
        清空
      </el-button>
    </div> -->
    <!-- </el-dialog> -->


    <!-- <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import { fetchsetting , fetchsetstore, fetchsetdelall, fetchBanner, uploadImg, fetchstoreban, fetchdelbanner} from '@/api/article'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
const __ = {
  formatDate: (date, fmt) => {
    const padLeftZero = (str) => {
      return ('00' + str).substr(str.length)
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
  }
}
export default {
  name: 'yuyue',
  components: { Pagination },
  filters: {
    formatDate(time) {
      if(!time) return '-';
      return __.formatDate(new Date(time - 0), 'yyyy-MM-dd hh:mm:ss')
    },
  },
  data() {
    return {
      baseimgurl: '',
      imgurl: '',
      pic_files: '',
      isupload: false,
      textMap: {
        update: '编辑banner',
        create: '创建banner'
      },
      dialogStatus: 'create',
      dialogFormVisible: false,

      timerules: [['','']],
      list: [],
      tableLoading: true,
      total: 0,
      listQuery: {
        page: 0,
        phone: '',
        limit: 20
      },
      temp: {
        name: '',
        content: '',
        ad_position_id: 1,
        enabled: true,
        end_time: 0,
        image_url: '',
        link: '',
        media_type: 1
      },
      rules: {
        name: [{ required: true, message: '名称 is required', trigger: 'blur' }],
        content: [{ required: true, message: '简介 is required', trigger: 'blur' }],
      },

    }
  },
  created() {
    // this.getList();
    this.getbanner();
  },
  methods: {

    handleUpdate(row) {

      this.dialogStatus = 'update'
      this.temp = row
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.tableLoading = true;
            const tempData = Object.assign({}, this.temp)
            tempData['end_time'] = tempData.id?tempData['end_time']:new Date().getTime();
            tempData['enabled'] = Number(tempData['enabled']);
          fetchstoreban(tempData).then(() => {
            // this.list.unshift(this.temp)
            // this.listLoading = false;
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Successfully',
              type: 'success',
              duration: 2000
            })
            this.getbanner()
            this.tableLoading = false;
          },()=>{
            this.tableLoading = false;
          })
        }
      })
    },
    handleDelete(row, index) {
      this.tableLoading = true;
      this.$confirm(`确定要删除？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fetchdelbanner({id: row.id}).then((res) => {
          this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
          this.getbanner();
          this.tableLoading = false;
        })

      }).catch(() => {
        this.tableLoading = false;
      });
    },
    handleCreate() {
      // this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    onUploadxqimg(file) {
      const _this = this
      console.log(file)
      const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('只能上传jpg/png图片!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
        return false;
      }
      this.pic_files = file;
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
        // console.log(e.target)
        _this.imgurl = this.result;
          // console.log(this.result)//图片的base64数据
      }
    },
    uploadimgsend() {
      const  _this = this;
      var formFile = new FormData()
      formFile.append('file', this.pic_files.raw)
      formFile.append('fileName', 'banner')
      this.isupload = true
      uploadImg(formFile).then(response => {
        // _this.temp.xqimg = 'http://localhost:8092/public'+response.data;
        _this.temp.image_url = response.fileUrl
        _this.isupload = false
        _this.pic_files = null;
        _this.imgurl = '';
      })
      return false
    },
    addrules(){
      this.timerules.push(['','']);
    },
    delrules(index){
      this.timerules.splice(index, 1)
    },
    updateData(){
      // let max = this.temp.timerules.length;
      let resTimeData = [];
      const stimedom = this.$refs.stime;
      const etimedom = this.$refs.etime;

      stimedom.forEach((item, i) => {
        let a = item.value, b = etimedom[i].value;
        if(!a || !b) return;
        resTimeData.push({v_keys: 'stime', v_vals: a, v_type: '_time'+i});
        resTimeData.push({v_keys: 'etime', v_vals: b, v_type: '_time'+i});
        // console.log(item.value)
      });
      if(!resTimeData.length)return ;
      this.listLoading = true;
      resTimeData['enabled'] = Number(resTimeData['enabled']);
      fetchsetstore({data: resTimeData}).then(res => {
        // this.temp = res.data
        // console.log(res)
        this.getList()
      })
      console.log(resTimeData)
    },
    deleallData(){

      this.$confirm(`确定要删除所有时间字段？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fetchsetdelall().then((res) => {
          // console.log(res);
          this.listLoading = true;
          this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })

      }).catch(() => {
        this.listLoading = false;
      });
    },
    getList() {
      this.listLoading = true
      fetchsetting().then(res => {
        // this.temp = res
        this.timerules = res.timesList;
        if(!this.timerules.length)this.addrules();
        console.log(res)
      })
    },
    getbanner() {
      this.tableLoading = true
      fetchBanner().then(res => {
        res.data.forEach(el => {
          el['enabled'] = Boolean(el['enabled']);
        })
        this.list = res.data;
        this.total = res.count;
        this.tableLoading = false;
        // this.temp = res
        // this.timerules = res.timesList;
        // if(!this.timerules.length)this.addrules();
        // console.log(res)
      })
    },

  }
}
</script>

<style media="screen" scoped>
  .setbox{
    display: flex;
  }
  .setbox .box{
    flex: 1
  }
  .inputsty{
    width: 130px;
    height: 32px;
    padding: 0 10px;
    border-radius: 4px;
    outline: none;
    /* border-color: #f1f1f1; */
    border: 1px solid #ccc;
  }
</style>
